package com.example.musicaiap.ui.home

import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AudioFile
import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Album // Placeholder for Album icon
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.LibraryMusic
import androidx.compose.material.icons.filled.Menu // Placeholder for Playlist icon
import androidx.compose.material.icons.filled.Mic // Placeholder for Artist icon
import androidx.compose.material.icons.filled.MoreHoriz // Use MoreHoriz for bottom nav
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.MusicNote
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color // Import Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.util.UnstableApi
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.example.musicaiap.R
import com.example.musicaiap.domain.model.Playlist
import com.example.musicaiap.domain.model.Song
import com.example.musicaiap.mvi.base.CollectState
import com.example.musicaiap.navigation.NavigationState
import com.example.musicaiap.service.PlaybackState
import com.example.musicaiap.ui.components.MiniPlayer
import com.example.musicaiap.ui.components.PlaylistBottomSheet
import com.example.musicaiap.ui.community.CommunityViewModel // Will be removed if CommunityContent is removed
import com.example.musicaiap.ui.library.LibraryScreen // Import the new screen
import com.example.musicaiap.ui.more.MoreScreen // Import the new screen
import com.example.musicaiap.ui.player.PlayerContract // Keep for MiniPlayer/PlayerViewModel interaction if needed
import com.example.musicaiap.ui.player.PlayerViewModel // Keep for PlayerController access
import com.example.musicaiap.ui.theme.QQGreen // Keep for MiniPlayer, etc.
// Removed QQTagBackground as it was used in removed components
import com.example.musicaiap.ui.theme.RedAccent // Import the new color

/**
 * 主页屏幕
 */
@OptIn(ExperimentalMaterial3Api::class)
@UnstableApi
@Composable
fun HomeScreen(
    modifier: Modifier = Modifier,
    viewModel: HomeViewModel = hiltViewModel(),
    communityViewModel: CommunityViewModel = hiltViewModel(),
    playerViewModel: PlayerViewModel = hiltViewModel(),
    onPlaylistClick: (String) -> Unit,
    onPlayerClick: () -> Unit,
    onPermissionResult: ((Boolean) -> Unit) -> Unit,
    navigationState: NavigationState,
    onNavigateToAbout: () -> Unit // Add the navigation callback parameter
) {
    val snackbarHostState = remember { SnackbarHostState() }
    var selectedTabIndex by remember { mutableIntStateOf(0) }

    // 默认选中第一个标签（媒体库）
    // 使用 NavigationState 中的 lastSelectedTabIndex 初始化，如果 HomeScreen 重组则恢复状态
    var selectedNavItem by remember { mutableIntStateOf(navigationState.lastSelectedTabIndex) }

    // 当selectedNavItem变化时，更新NavigationState
    LaunchedEffect(selectedNavItem) {
        navigationState.lastSelectedTabIndex = selectedNavItem
    }

    // 添加播放列表底部弹窗显示状态控制
    var isPlaylistBottomSheetVisible by remember { mutableStateOf(false) }

    val uiState by viewModel.CollectState { effect ->
        when (effect) {
            is HomeContract.Effect.NavigateToPlaylist -> {
                onPlaylistClick(effect.playlistId)
            }
            is HomeContract.Effect.ShowToast -> {
                snackbarHostState.showSnackbar(effect.message)
            }
            is HomeContract.Effect.NavigateToPlayer -> {
                onPlayerClick()
            }
            is HomeContract.Effect.RequestStoragePermission -> {
                // 请求权限并在回调中处理结果
                println("HomeScreen: 收到权限请求效应")
                onPermissionResult { granted ->
                    println("HomeScreen: 权限请求结果返回: $granted")
                    // 将权限结果发送给ViewModel处理
                    viewModel.sendIntent(HomeContract.Intent.PermissionResult(granted))
                }
            }
            else -> {}
        }
    }

    // 获取收藏歌曲数据
    val favoriteSongs by communityViewModel.favoriteSongs.collectAsState(initial = emptyList())
    val isLoadingFavorites by communityViewModel.isLoading.collectAsState()

    // 获取PlayerController
    val playerController = playerViewModel.playerController

    // 获取当前播放列表
    val currentPlaylist by playerController.playerState.collectAsState()

    // 发送加载内容意图
    LaunchedEffect(key1 = true) {
        viewModel.sendIntent(HomeContract.Intent.LoadContent)
    }

    // 添加播放列表底部弹窗
    PlaylistBottomSheet(
        isVisible = isPlaylistBottomSheetVisible,
        onDismiss = { isPlaylistBottomSheetVisible = false },
        playQueue = currentPlaylist.currentPlaylist ?: emptyList(),
        currentSong = uiState.currentPlayingSong,
        onSongClick = { song ->
            viewModel.sendIntent(HomeContract.Intent.ClickSong(song))
            isPlaylistBottomSheetVisible = false
        }
    )

    Scaffold(
        containerColor = Color.Transparent, // Make Scaffold background transparent
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
        bottomBar = {
            Column {
                // Mini播放器
                MiniPlayer(
                    isVisible = uiState.currentPlayingSong != null,
                    currentSong = uiState.currentPlayingSong,
                    isPlaying = uiState.isPlaying,
                    progress = if (uiState.duration > 0) {
                        uiState.currentPosition.toFloat() / uiState.duration.toFloat()
                    } else {
                        0f
                    },
                    currentPosition = uiState.currentPosition,
                    duration = uiState.duration,
                    onPlayPause = {
                        viewModel.sendIntent(HomeContract.Intent.TogglePlayPause)
                    },
                    onSkipNext = {
                        viewModel.sendIntent(HomeContract.Intent.NextSong)
                    },
                    onSkipPrevious = {
                        viewModel.sendIntent(HomeContract.Intent.PreviousSong)
                    },
                    onSeek = { progress ->
                        if (uiState.duration > 0) {
                            val seekPosition = (progress * uiState.duration).toLong()
                            viewModel.sendIntent(HomeContract.Intent.SeekTo(seekPosition))
                        }
                    },
                    onPlayerClick = onPlayerClick,
                    onPlaylistClick = { isPlaylistBottomSheetVisible = true },
                    isInPlaylistScreen = navigationState.isInPlaylistScreen
                )

                // 底部导航栏 - 添加动画效果
                AnimatedVisibility(
                    visible = !navigationState.isInPlaylistScreen,
                    enter = fadeIn(animationSpec = tween(300)) + expandVertically(),
                    exit = fadeOut(animationSpec = tween(300)) + shrinkVertically()
                ) {
                    NavigationBar(
                        containerColor = MaterialTheme.colorScheme.surface // 通常是白色
                        // Removed duplicate containerColor
                        // contentColor = MaterialTheme.colorScheme.onSurface // 未选中项的颜色 - This is default
                    ) {
                        // 媒体库 Tab
                        NavigationBarItem(
                            icon = { Icon(Icons.Filled.LibraryMusic, contentDescription = "媒体库") },
                            label = { Text("媒体库", fontSize = 12.sp) },
                            selected = selectedNavItem == 0,
                            onClick = { selectedNavItem = 0 }, // 切换选中项
                            colors = NavigationBarItemDefaults.colors(
                                selectedIconColor = RedAccent, // 选中时红色
                                selectedTextColor = RedAccent, // 选中时红色
                                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant, // 未选中时灰色
                                unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant, // 未选中时灰色
                                indicatorColor = MaterialTheme.colorScheme.surface // 指示器颜色与背景相同，使其不可见
                            )
                        )
                        // 更多 Tab
                        NavigationBarItem(
                            icon = { Icon(Icons.Filled.MoreHoriz, contentDescription = "更多") },
                            label = { Text("更多", fontSize = 12.sp) },
                            selected = selectedNavItem == 1,
                            onClick = { selectedNavItem = 1 }, // 切换选中项
                            colors = NavigationBarItemDefaults.colors(
                                selectedIconColor = RedAccent, // 选中时红色
                                selectedTextColor = RedAccent, // 选中时红色
                                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant, // 未选中时灰色
                                unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant, // 未选中时灰色
                                indicatorColor = MaterialTheme.colorScheme.surface // 指示器颜色与背景相同，使其不可见
                            )
                        )
                    }
                }
            }
        }
    ) { paddingValues ->
        // The outer Box in MainActivity now handles the global background.
        // This Box is for the content area within the Scaffold padding.
        Box(
            modifier = Modifier
                .fillMaxSize()
                // Removed background modifier here, background is handled globally
                .padding(paddingValues) // Apply padding from Scaffold
        ) {
            // Removed isLoading and error checks as they are no longer in uiState
            // Always display content based on selectedNavItem
            // 根据选中的导航项显示不同内容
            when (selectedNavItem) {
                0 -> LibraryScreen(
                        modifier = Modifier.fillMaxSize(),
                        localSongs = uiState.localSongs, // Pass local songs
                        onSongClick = { song -> viewModel.sendIntent(HomeContract.Intent.ClickSong(song)) },
                        onMoreClick = { song -> /* TODO: Implement More options for song */ },
                        onPlaylistCategoryClick = { /* TODO: Navigate to Playlist screen */ },
                        onAlbumCategoryClick = { /* TODO: Navigate to Album screen */ },
                        onArtistCategoryClick = { /* TODO: Navigate to Artist screen */ },
                        onFolderCategoryClick = { /* TODO: Navigate to Folder screen */ },
                        onSearchClick = { /* TODO: Implement Search functionality */ },
                        onMoreOptionsClick = { /* TODO: Implement More options for library */ }
                    )
                    1 -> MoreScreen(
                        modifier = Modifier.fillMaxSize(),
                        onNavigateToAbout = onNavigateToAbout // Pass the callback to MoreScreen
                    )
                    // Removed old cases (including CommunityContent)
                    else -> {
                        // Placeholder for potential future tabs
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text("未定义内容", style = MaterialTheme.typography.bodyLarge)
                        }
                    }
                }
            // } // Removed the 'else' block for isLoading/error
        }
    }
}

// Removed QQMusicHomeContent Composable
// Removed SearchBar Composable
// Removed RecommendCard Composable
// Removed PopularSongItem Composable
// Removed LocalMusicContent Composable
// Removed LocalSongItem Composable
// Removed formatDuration function
// Removed CommunityContent Composable

@Preview(showBackground = true)
@Composable
private fun HomeScreenPreview() {
    val navState = remember { NavigationState() }
    HomeScreen(
        onPlaylistClick = {},
        onPlayerClick = {},
        onPermissionResult = {},
        navigationState = navState,
        onNavigateToAbout = {} // Provide a dummy callback for preview
    )
}
